<?php

namespace app\admin\controller;

use think\Controller;

class Api extends Controller {

	/**
	 * 提现代付
	 * @author lukui  2017-09-05
	 * @param  [type] $balance  提现列表
	 * @param  [type] $userinfo 用户名称
	 * @param  [type] $bank     银行账户
	 * @return [type]           返回信息
	 */
	/*	 * ****************************************************************** */
	//杉德代付接口
	/*	 * ***************************************************************** */

	public function daifu($balance, $userinfo, $bank) {
		//是否已经提现
		if ($balance['isverified'] != 9) {
			return WPreturn('该订单已处理!', -1);
		}

		require_once __DIR__ . '/../../../pay/sandpay/sdk/autoload.php';
		require_once __DIR__ . '/../../../pay/sandpay/import/handle.php';
		/*
		  $host = 'http://61.129.71.103:7970/agent-main/openapi';
		  $merId = '14379449';
		  $cert = array(
		  //测试环境证书
		  'pubPath' => __DIR__ . '/../../../pay/sandpay/import/cert/SAND_PUBLIC_KEY.cer',
		  'priPath' => __DIR__ . '/../../../pay/sandpay/import/cert/MID_RSA_PRIVATE_KEY.pfx',
		  'certPwd' => '123456'
		  );
		 */

		$host = PAY_HOST;
		$merId = SAND_MID;
		$cert = array(
			//生产环境证书
			'pubPath' => PUB_KEY_PATH,
			'priPath' => PRI_KEY_PATH,
			'certPwd' => CERT_PWD
		);

		$handle = new \handle($cert);
		$params = array(
			'transCode' => 'RTPM', //实时代付
			'merId' => $merId, //测试：14379449     正式：11050857
			'url' => $host . '/agentpay',
			'pt' => array(
				"orderCode" => $balance['bpid'] . time(), //订单号  合作商户唯一，建议订单号中包含日期
				'version' => '01',
				"productId" => "00000004", //产品ID    00000001   代收对公    00000002  代收对私     00000003  代付对公     00000004  代付对私
				"tranTime" => date('YmdHis', time()), //交易时间   合作商户发起时间
				"timeOut" => date('YmdHis', time() + 3600 * 12), //订单超时时间   不填默认24小时
				"tranAmt" => str_pad(sprintf("%.2f", round($balance['bpprice'] * (100 - $balance['reg_par']) / 100, 2)) * 100, 12, "0", STR_PAD_LEFT), //金额  精确到分
				"currencyCode" => "156", //币种   默认156
				"accAttr" => "0", //账户属性   0-对私(默认)  1-对公    取值需与产品编码一致
				"accNo" => $bank['accntno'], //收款人账户号
				"accType" => "4", //账号类型   3-公司账户   4-银行卡
				"accName" => $bank['accntnm'], //收款人账户名
				//        'provNo' => 'sh',
				//        'cityNo' => 'sh',
				//'bankName' => 'cbc',
				//'bankType' => '1',
				'remark' => 'pay',
				"payMode" => "1", //付款模式   1-	商户预存款，默认      2-	在线支付账户    3-	银行卡账户(代扣模式，需另签协议)
				"channelType" => "07", //渠道类型  07：互联网08：移动端    表示商户业务使用场景，可默认填07
				"noticeUrl" => "http://{$_SERVER['HTTP_HOST']}/admin/api/daifu_sande_notify.html", // //代付结果通知地址
		));
		file_put_contents("sandpay_daifu.log", var_export($params, true) . "\r\n", FILE_APPEND);
		$res = $handle->execute($params);
		file_put_contents("sandpay_daifu.log", var_export($res, true) . "\r\n", FILE_APPEND);
		if ($res) {
			$resp = json_decode($res, true);
			file_put_contents("sandpay_daifu.log", var_export($resp, true) . "\r\n", FILE_APPEND);
			if ($resp['respCode'] == "0") {
				return WPreturn("代付请求提交成功", 1);
			} else {
				return WPreturn($resp['respDesc'], -1);
			}
		} else {
			return WPreturn("代付失败", -1);
		}


		/*


		  require(__DIR__ . '/../../../pay/sandpay/common.php');
		  header("Content-Type:text/html;charset=utf-8");
		  date_default_timezone_set("Asia/Shanghai");
		  $prikey = loadPk12Cert(PRI_KEY_PATH, CERT_PWD);
		  $pubkey = loadX509Cert(PUB_KEY_PATH);
		  $postData = array(
		  "version" => "01", //版本号
		  "productId" => "00000004", //产品ID    00000001   代收对公    00000002  代收对私     00000003  代付对公     00000004  代付对私
		  "tranTime" => date('YmdHis', time()), //交易时间   合作商户发起时间
		  "orderCode" => $balance['bpid'] . '_' . time(), //订单号  合作商户唯一，建议订单号中包含日期
		  "timeOut" => date('YmdHis', time() + 3600 * 12), //订单超时时间   不填默认24小时
		  "tranAmt" => sprintf("%.2f", round($balance['bpprice'] * (100 - $balance['reg_par']) / 100, 2)) * 100, //金额  精确到分
		  "currencyCode" => "156", //币种   默认156
		  "accAttr" => "0", //账户属性   0-对私(默认)  1-对公    取值需与产品编码一致
		  "accType" => "4", //账号类型   3-公司账户   4-银行卡
		  "accNo" => $bank['accntno'], //收款人账户号
		  "accName" => $bank['accntnm'], //收款人账户名
		  //"provNo" => "", //收款人开户省份编码
		  //"cityNo" => "", //收款人开会城市编码
		  //"bankName" => "", //收款账户开户行名称   accAttr =1时必填
		  //"bankType" => "", //收款人账户联行号
		  "remark" => "pay", //摘要
		  "payMode" => "1", //付款模式   1-	商户预存款，默认      2-	在线支付账户    3-	银行卡账户(代扣模式，需另签协议)
		  "channelType" => "07", //渠道类型  07：互联网08：移动端    表示商户业务使用场景，可默认填07
		  //"extendParams" => "", //业务扩展参数   JSON结构{ busiType：业务类型 2-提现    storeId：门店编号 ANS0..20  accountDate：商户记账日期 ANS8}
		  //"reqReserved" => "", //请求方保留域
		  "noticeUrl" => "http://{$_SERVER['HTTP_HOST']}/admin/api/daifu_sande_notify.html", // //代付结果通知地址
		  //"extend" => "", //扩展域
		  );
		  $sign = sign($postData, $prikey);
		  $post = array(
		  'charset' => 'utf-8',
		  'signType' => '01',
		  'data' => json_encode($postData),
		  'sign' => $sign
		  );
		  $result = http_post_json(PAY_HOST . '/agentpay', $post);
		  file_put_contents("sandpay_daifu.log", var_export($postData, true) . "\r\n", FILE_APPEND);
		  file_put_contents("sandpay_daifu.log", var_export($result, true) . "\r\n", FILE_APPEND);
		  parse_str(urldecode($result), $arr);
		  $resp = json_decode($arr['data'], true);
		  file_put_contents("sandpay_daifu.log", var_export($resp, true) . "\r\n", FILE_APPEND);


		  if ($resp['head']['respCode'] == "000000") {
		  return WPreturn($resp['head']['respCode'], 1);
		  } else {
		  return WPreturn($resp['head']['respCode'], -1);
		  }
		 * *
		 */
	}

	//回调接口
	public function daifu_sande_notify() {
		file_put_contents("sandpay_daifu_notify.txt", date("Y-m-d H:i:s") . "  " . "异步通知返回报文：" . var_export($_POST, true) . "\r\n", FILE_APPEND);
		/*
		  require(__DIR__ . '/../../../pay/sandpay/common.php');
		  date_default_timezone_set("Asia/Shanghai");
		  file_put_contents("sandpay_daifu_notify.txt", date("Y-m-d H:i:s") . "  " . "异步通知返回报文：" . var_export($_POST, true) . "\r\n", FILE_APPEND);
		  $pubkey = loadX509Cert(PUB_KEY_PATH);
		  if ($_POST) {
		  $str = $_POST;
		  $sign = $str['sign']; //签名
		  $signType = $str['signType']; //签名方式
		  $data = stripslashes($str['data']); //支付数据
		  $charset = $str['charset']; //支付编码
		  $result = json_decode($data, true); //data数据
		  file_put_contents("sandpay_daifu_notify.txt", date("Y-m-d H:i:s") . "  " . "异步通知返回报文：" . var_export($result, true) . "\r\n", FILE_APPEND);
		  //if (verify($data, $sign, $pubkey)) {
		  //签名验证成功
		  if ($result['body']['orderStatus'] == "1" || $result['head']['respCode'] == "000000") {

		  //$OrderID = $result['body']['orderCode'];
		  //$Amt = intval($result['body']['totalAmount']);
		  //$Amt = round($Amt / 100, 2);
		  //file_put_contents("sd_notifyUrl_log.txt", date("Y-m-d H:i:s") . "  " . "回调成功，OrderID：{$OrderID}，Amt：{$Amt}\r\n", FILE_APPEND);
		  //$this->notify_ok_dopay($OrderID, $Amt);
		  }
		  echo "respCode=000000";
		  exit;

		  } else {
		  file_put_contents("sd_notifyUrl_log.txt", date("Y-m-d H:i:s") . "  " . "失败\r\n", FILE_APPEND);
		  //签名验证失败
		  exit;
		  }
		  } */
	}

	/*	 * ****************************************************************** */

	//聚合支付 代付接口部分
	/*	 * ***************************************************************** */

	private function daifuConfig() {
		return array(
			"MerchantID" => "MD201710200000001136", //商户编号
			"md5Key" => "rU7eLccS523K2TVDMNIQR0SxAArvgvsh", //md5密钥
			"payUrl" => "http://www.bisrec.com/aggpay/gateway/api/pay", //post提交接口
			"AppID" => "", //公众号appid
			"OpenID" => "", //微信openid
			"NotifyUrl" => "http://{$_SERVER['HTTP_HOST']}/index/pay/juhenotify.html", //异步通知地址
			"ReturnUrl" => "http://{$_SERVER['HTTP_HOST']}/index/index/index.html", //同步返回地址
			"PayPwd" => "123456", //支付密码	（支付密码+工作密钥）MD5加密,商户必填
			"PwdKey" => "VOSZVO2JXM2JPZ03AV6X6YCTNA00FSVN", //支付密码	（支付密码+工作密钥）MD5加密,商户必填
		);
	}

	public function daifu_old($balance, $userinfo, $bank) {

		//是否已经提现
		if ($balance['isverified'] != 9) {
			return WPreturn('该订单已处理!', -1);
		}
		$daifuConfig = $this->daifuConfig();

		//代付信息
		header("Content-Type:text/html;charset=utf-8");
		$data = array(
			"TradeType" => "bis.pay.payment", //N	交易类型	bis.pay.payment
			"OperatorID" => $daifuConfig['MerchantID'], //Y操作员	默认商户编号
			"PayType" => "0101", //N支付类型	"0101-单笔实时代付
			"TerminalType" => "PC", //Y终端类型 Android;IOS;PC;Others
			"PayPWD" => md5($daifuConfig['PayPwd'] . $daifuConfig['PwdKey']), //N支付密码	（支付密码+工作密钥）MD5加密,商户必填
			"MerchantID" => $daifuConfig['MerchantID'], //N商户编号
			"BankID" => "", //Y银行代码	存折必须填写
			//"OrderID" => $balance['bpid'] . '_' . $balance['bptime'], //N	订单号
			"OrderID" => $balance['bpid'] . '_' . time(), //N	订单号
			"BankAccountType" => "00", //Y	银行账户类型	00银行卡，01存折，02信用卡。不填默认为银行卡00。
			"BankAccountNo" => $bank['accntno'], //N	银行账号
			"BankAccountName" => $bank['accntnm'], //N	银行账户名称
			"Province" => "", //Y	开户行所在省
			"City" => "", //Y	开户行所在市	如北京市，不能填北京
			"BankName" => $bank['bank_nm'], //Y	开户行名称
			"AccountProp" => "0", //Y	账号属性	0-对私 1-对公
			"CardType" => "0", //Y	开户证件类型 0:身份证,1:户口簿，2:护照,3.军官证,4.士兵证，5. 港澳居民来往内地通行证,6. 台湾同胞来往内地通行证,7. 临时身份证,8. 外国人居留证,9. 警官证,A.组织机构代码证，B.三证合一 X.其他证件
			"CardNum" => $bank['scard'], //Y	证件号码
			"Tel" => $bank['phone'], //Y	手机号码（预留在银行的）
			"BranchBankID" => "", //Y	支行号	见附件
			"DeviceID" => "", //Y	设备号	
			"MachineIP" => $this->getClientIp(), //N	终端IP	订单生成的机器IP
			"NotifyUrl" => "http://{$_SERVER['HTTP_HOST']}/admin/api/daifurefund.html", //N	通知地址
			"SubmitTime" => date("YmdHis"), //N	订单提交时间	格式：yyyyMMddHHmmss
			"Amt" => sprintf("%.2f", round($balance['bpprice'] * (100 - $balance['reg_par']) / 100, 2)) * 100, //N	交易金额	单位为分，不含小数点
			"Summary" => "提现转账", //Y	交易附言
			//"Sign" => "bis.pay.payment",
		);

		$data = $this->paraFilter($data);
		$data['Sign'] = $this->juheSign($data, $daifuConfig['md5Key']);
		//$this->curlPost($daifuConfig['payUrl'], $data);
		$Reply = $this->curlPost($daifuConfig['payUrl'], $data);
		$result = array();
		parse_str($Reply, $result);
		/*
		  PlatSerial	String(40)	Y	平台交易流水号
		  OperatorID	String(40)	Y	操作员ID
		  OrderID	String(40)	N	订单号
		  MerchantID	String(40)	Y	商户编号
		  Amt	String(16)	Y	交易金额	单位为分，不含小数点
		  Sign	String(32)	N	签名,详见数据签名说明
		  RetStatus	String(4)	N	业务状态	0表示接受，1或者其他标识未接受
		  RetDesc	String(128)	Y	状态描述
		  RetCode	String(4)	N	返回代码	参照返回码
		  RetMsg	String(128)	Y	描述信息
		 */
		file_put_contents("juhepay.log", date("Y-m-d H:i:s") . ":" . var_export($data, true) . "\r\n", FILE_APPEND);
		file_put_contents("juhepay.log", date("Y-m-d H:i:s") . ":" . var_export($Reply, true) . "\r\n", FILE_APPEND);
		if ($result['RetStatus'] == '0') {
			return WPreturn($result['RetMsg'], 1);
		} else {
			return WPreturn($result['RetMsg'], -1);
		}
	}

	public function daifurefund() {
		date_default_timezone_set('PRC');
		error_reporting(0);
		set_time_limit(0);
		$juheConfig = $this->juheConfig();
		file_put_contents("juhepay.log", var_export($_POST, true), FILE_APPEND);
		if ($this->juheSignVerify($_POST, $juheConfig['md5Key'])) {
			$notifyArray = array(// 返回字段
				"RetStatus" => $_POST["RetStatus"], // 返回状态  //0表示成功非0表示失败此字段是通信标识，非交易标识，交易是否成功需要查看 DealStatus 来判断
				"RetDesc" => $_POST["RetDesc"], // 状态描述
				"DealStatus" => $_POST["DealStatus"], // 交易状态  //0已支付，1未支付，其他失败
				"RetCode" => $_POST["RetCode"], // 返回码
				"RetMsg" => $_POST["RetMsg"], //描述
				"Sign" => $_POST["Sign"], //签名,详见数据签名说明
				"PayType" => $_POST["PayType"], //支付类型  0203-微信扫码支付;0204-支付宝扫码支付;0205-微信app支付;0207-微信公众号支付
				"MerchantID" => $_POST["MerchantID"], //商户编号
				"OrderID" => $_POST["OrderID"], //订单号
				"Subject" => $_POST["Subject"], //商品名称
				"TradeTime" => $_POST["TradeTime"], //订单交易时间  格式：yyyyMMddHHmmss
				"Amt" => $_POST["Amt"], //交易金额  单位为分，不含小数点
				"Summary" => $_POST["Summary"], //交易附言
				"Status" => $_POST["Status"], //订单状态  01：未支付 ；02：已支付；03：已关闭；04：支付失败；05：订单超时；
			);
			if ($notifyArray['RetCode'] == '0000') {
				//提现成功
				$_data['isverified'] = 1;
			} else {
				$_data['isverified'] = -1;
				$_data['remarks'] = $notifyArray['RetMsg'];
			}
			file_put_contents("juhepay.log", "SUCCESS", FILE_APPEND);
			echo "SUCCESS";
		} else {
			file_put_contents("juhepay.log", "验签失败", FILE_APPEND);
			echo "验签失败";
			$_data['isverified'] = -1;
			$_data['remarks'] = "签名验证失败";
		}


		//处理提现申请
		$res_order = explode("_", $notifyArray['OrderID']);
		if ($res_order == 2) {
			$_data['bpid'] = $res_order[0];
		} else {
			$_data['bpid'] = 7130;  //测试失误，但是要成功！
		}
		db('balance')->update($_data);
	}

	/*

	  public function daifu($balance,$userinfo,$bank)
	  {

	  //是否已经提现
	  if($balance['isverified'] != 0){
	  return WPreturn('该订单已处理!',-1);
	  }


	  //代付信息
	  header("Content-Type:text/html;charset=utf-8");
	  $data['merId'] = 'M1708231621510004';
	  $data['userId'] = '13378685767';
	  $data['carId'] = $bank['accntno'];
	  $data['openName'] = $bank['accntnm'];
	  $data['openBank'] = $bank['bank_nm'];
	  $data['userOrder'] = $balance['bpid'].'_'.$balance['bptime'];
	  $data['phone'] =$bank['phone'];
	  $data['liqType'] = 'T0';
	  $data['openBank'] = $bank['bank_nm'];
	  $data['voucher'] = "身份证";
	  $data['voucherId'] = $bank['scard'];
	  $data['reqUrl'] = "http://".$_SERVER['SERVER_NAME']."/admin/api/daifurefund.html";
	  $data['money'] = sprintf("%.2f",round($balance['bpprice']*(100-$balance['reg_par'])/100,2));


	  $sn			= 'ca5b1fa291';
	  $data['reqType']='payWith';
	  //签名串
	  $chkValue=md5($data['reqType'].$data['merId'].$data['userId'].$data['userOrder'].$data['money'].$data['reqUrl'].$data['carId'].$data['openName'].$data['openBank'].$data['phone'].$data['voucher'].$data['voucherId'].$sn);

	  $data['chkValue']=$chkValue;

	  $url="http://pay.goldepay.cn/mobile/wdl/payWith.do";


	  $ch = curl_init ();
	  curl_setopt ( $ch, CURLOPT_URL,$url);//抓取指定网页
	  curl_setopt ( $ch, CURLOPT_POST, 1 );//设置header
	  curl_setopt ( $ch, CURLOPT_HEADER, 0 );//设置header
	  curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );//要求结果为字符串且输出到屏幕上
	  curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data);
	  $return = curl_exec ( $ch );
	  curl_close ( $ch );


	  $arr = json_decode($return,1);

	  if($arr['resultCode'] == '0000'){
	  return WPreturn($arr['resultMsg'],1);
	  }else{
	  return WPreturn($arr['resultMsg'],-1);
	  }


	  }


	  public function daifurefund()
	  {


	  //以下是post接受的传递过来的参数
	  $merId 		= $_POST['merId'];   		 //商户号
	  $userOrder 	= $_POST['userOrder']; 		 //接收传递的订单号
	  $money		= $_POST['money']; 		 	 //金额
	  $resultCode	=$_POST['resultCode'];	     //状态码
	  $resultMsg	=$_POST['resultMsg']; 	     //返回错误
	  $date		=$_POST['date'];  			 //时间
	  $chkValue 	= $_POST['chkValue'];  		 //获取签名串
	  $sn			= "ca5b1fa291";  						 //商户密匙（form表单中未提交在这重新输入值进行验证）
	  $md55		= md5($merId.$userOrder.$money.$resultCode.$resultMsg.$date.$sn);//利用商户密匙重新生成md5加密串与接受的签名串进行验证

	  if($resultCode == "0000"){  			 //判断返回的提现状态
	  if($md55 == $chkValue){  				 //判断MD5加密串是否正确（利用商户密匙）
	  $_data['isverified'] = 1;
	  printf('success');				 //打印流水号给支付系统检索用来确认商户系统已经收到该笔流水号的交易返回应答
	  }
	  }else{
	  $_data['isverified'] = -1;
	  $_data['remarks'] = $resultMsg;
	  }

	  $res_order = explode("_", $userOrder);
	  if($res_order == 2){
	  $_data['bpid'] = $res_order[0];
	  }else{
	  $_data['bpid'] = 7130; 	//测试失误，但是要成功！
	  }
	  db('balance')->update($_data);

	  } */

	public function getClientIp() {
		if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$ip = getenv('HTTP_CLIENT_IP');
		} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$ip = getenv('REMOTE_ADDR');
		} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		preg_match("/[\d\.]{7,15}/", $ip, $onlineipmatches);
		$ip = empty($onlineipmatches[0]) ? 'unknown' : $onlineipmatches[0];
		return $ip;
	}

	public function paraFilter($para) {
		$para_filter = array();
		while (list ($key, $val) = each($para)) {
			if ($key == "Sign" || $key == "sign_type" || $val == "")
				continue;
			else
				$para_filter[$key] = $para[$key];
		}
		return $para_filter;
	}

	public function juheSign($data, $md5Key) {
		ksort($data);
		reset($data);
		$signString = "";
		foreach ($data as $k => $v) {
			if ($v !== "") {
				$signString .= "{$k}={$v}&";
			}
		}
		return strtoupper(md5($signString . "Key={$md5Key}"));
	}

	public function juheSignVerify($data, $md5Key) {
		$sign = $data['Sign'];
		$data = $this->paraFilter($data);
		$mysgin = $this->juheSign($data, $md5Key);
		if ($mysgin == $sign) {
			return true;
		} else {
			return false;
		}
	}

	public function curlPost($url, $data) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		$content = curl_exec($ch);
		curl_close($ch);
		return $content;
	}

}
